<template>
    <div class="app">
        <router-view />

        <!-- 旋转进度条 -->
        <div v-if="indicatorVisible" class="app__indicator-wrap">
            <div class="ro-indicator-wrap dark">
                <div class="ro-indicator">
                    <DaisySpinner class="normal light"></DaisySpinner>
                </div>
            </div>
        </div>

        <!-- 用户信息授权登录 -->
        <van-popup v-model="showUserInfo" class="bind-popup" closeable :close-on-click-overlay="false" @click-close-icon="onCloseLogin">
            <div class="bind-popup__content">
                <div class="bind-popup__hint">您未登录，请先登录</div>
                <div class="bind-popup__btn-wrap">
                    <wx-component behavior="button"
                        class="bind-popup__btn btn btn-mobile btn-primary btn-large"
                        @click="onGetUserInfo" open-type="getUserInfo">
                        登录
                    </wx-component>
                </div>
            </div>
        </van-popup>

        <!-- 手机号授权弹窗 -->
        <van-popup v-model="showBindMobile" class="bind-popup" closeable :close-on-click-overlay="false" @click-close-icon="onCloseBind">
            <div class="bind-popup__content">
                <div class="bind-popup__hint">点击“确认”授权手机号</div>
                <div class="bind-popup__btn-wrap">
                    <wx-component behavior="button"
                        class="bind-popup__btn btn btn-mobile btn-primary btn-large"
                        open-type="getPhoneNumber"
                        @getphonenumber="onGetPhoneNumber">
                        确认
                    </wx-component>
                </div>
            </div>
        </van-popup>

        <ImagePopup />
    </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import DaisySpinner from '@/components/spinner/daisy.vue';
import store from '@/store';
import { ROUTE_NAME, STATUS_LOGIN_LOGINED } from './lib/constant';
import { objScene, tryCheckVersionUpdate } from './lib/utils';
import ImagePopup from '@/components/popup/imagePopup.vue';
import { api } from '@/lib/api';

@Component({
    name: 'App',
    components: {
        DaisySpinner,
        ImagePopup,
    },
})
export default class App extends Vue {
    /** 显示登陆弹窗 */
    public showUserInfo = store.state.auth.showUserInfo;
    /** 显示绑定手机号弹窗 */
    public showBindMobile = store.state.auth.showBindMobile;
    public indicatorVisible = false;

    public get req() {
        return store.state.utils.req;
    }
    public get storeShowUserInfo() {
        return store.state.auth.showUserInfo;
    }
    public get storeShowBindMobile() {
        return store.state.auth.showBindMobile;
    }
    /** 用户基础信息 */
    public get userBasicInfo() {
        return store.state.user.basicInfo;
    }
    public get pulldown() {
        return store.state.utils.pulldown;
    }

    @Watch('storeShowUserInfo')
    public onStoreShowUserInfo() {
        this.showUserInfo = this.storeShowUserInfo;
    }
    @Watch('showUserInfo')
    public onShowUserInfo() {
        store.commit('auth/showUserInfo', this.showUserInfo);
    }
    @Watch('storeShowBindMobile')
    public onStoreShowBindMobile() {
        this.showBindMobile = this.storeShowBindMobile;
    }
    @Watch('showBindMobile')
    public onShowBindMobile() {
        store.commit('auth/showBindMobile', this.showBindMobile);
    }
    @Watch('req')
    public onReqChange(val: number) {
        this.indicatorVisible = val > 0;
    }
    @Watch('pulldown')
    public onPulldownChange(val: number) {
        if (val === 0) {
            wx.stopPullDownRefresh();
        }
    }

    /**
     * 下拉刷新回调
     */
    public async pulldownRefresh() {
        store.commit('utils/startPulldown');
        await store.dispatch('user/getBasicInfo', {
            forceUpdate: true,
        });
        store.commit('utils/endPulldown');
    }
    /**
     * 获取用户信息
     */
    public async onGetUserInfo(e: { detail: any }) {
        if (wx.canIUse('getUserProfile')) {
            const userInfoRes = await api.getUserProfile({
                desc: '用于展示和提供更好的服务', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            }).catch(err => err);
            if (userInfoRes.errMsg.indexOf('getUserProfile:ok') > -1) {
                this.updateUserInfo(userInfoRes.encryptedData, userInfoRes.iv);
            }
            return;
        }
        if (wx.canIUse('getUserInfo')){
            const userInfoRes = await api.getUserInfo({
                withCredentials: true,
            }).catch(err => err);
            this.updateUserInfo(userInfoRes.encryptedData, userInfoRes.iv);
        }
    }
    public async updateUserInfo(encryptedData: string, iv: string) {
        store.commit('utils/startRequest');
        await store.dispatch('utils/syncWechat', {
            encryptedData,
            iv,
        });
        await store.dispatch('user/getBasicInfo', true);
        store.commit('utils/endRequest');

        this.showUserInfo = false;

        // 确认是否绑定手机号
        if (this.userBasicInfo && !this.userBasicInfo.mobile) {
            this.showBindMobile = true;
        }
    }
    /**
     * 获取用户信息
     */
    public async onGetPhoneNumber(e: { detail: any }) {
        if (e.detail.errMsg.indexOf('getPhoneNumber:ok') >= 0) {
            store.commit('utils/startRequest');
            const res = await store.dispatch('auth/bindMobile', {
                encryptedData: e.detail.encryptedData,
                iv: e.detail.iv,
            });
            store.commit('utils/endRequest');
            if (res.statusCode === 200 && res.data.status === 0) {
                await store.dispatch('user/getBasicInfo', true);
                // 授权完成后页面跳转，同时需要将弹窗去掉
                store.commit('auth/showBindMobile', false);

                // todo: 这里可能需要改成navigateTo
                const from = store.state.auth.bindMobileFrom;
                if (from) {
                    this.$router.push(from);
                } else {
                    this.$router.push({
                        name: ROUTE_NAME.HOME_INDEX,
                    });
                }
            } else {
                wx.showToast({
                    title: res.data.message,
                    icon: 'none',
                });
            }
        }
    }
    /**
     * 关闭login
     */
    public onCloseLogin() {
        wx.navigateBack();
    }
    /**
     * 关闭bind
     */
    public onCloseBind() {
        wx.navigateBack();
    }

    public created() {
        store.dispatch('order/getList', {
            status: 'init',
            offset: 0,
            count: 10,
        });

        // 执行更新逻辑
        tryCheckVersionUpdate();

        window.addEventListener('pagenotfound', (e: any) => {
            // console.log('target31', e);
        });
        window.addEventListener('pulldownrefresh', this.pulldownRefresh);

        window.addEventListener('wxload', (query: any) => {
            // console.log('target12', query);

            if (query.targeturl) {
                const targeturl = decodeURIComponent(query.targeturl);
                const route = this.$router.resolve(targeturl).route;
                if (route && route.query && route.query.referrer) {
                    const referrerId = route.query.referrer;
                    store.dispatch('user/addReferrer', {
                        referrerId,
                    });
                    store.commit('user/bindReferrer', {
                        referrerId,
                    });
                }
            }
            if (query.scene) {
                const sceneObj = objScene(query.scene);
                store.commit('utils/setScene', sceneObj);
                if (sceneObj.referrer) {
                    store.dispatch('user/addReferrer', {
                        referrerId: sceneObj.referrer,
                    });
                    store.commit('user/bindReferrer', {
                        referrerId: sceneObj.referrer,
                    });
                }

                if (sceneObj.type === 'good') {
                    this.$router.push({
                        name: ROUTE_NAME.PRODUCT_DETAIL,
                        params: {
                            productId: sceneObj.id,
                        },
                        query: {
                            referrer: sceneObj.referrer,
                        },
                    });
                } else {
                    this.$router.push({
                        name: ROUTE_NAME.PKG_DETAIL,
                        params: {
                            pkgId: sceneObj.id,
                        },
                        query: {
                            referrer: sceneObj.referrer,
                        },
                    });
                }
            }
        });
    }
    public beforeDestroy() {
        window.removeEventListener('pulldownrefresh', this.pulldownRefresh);
    }
}
</script>

<style lang="less">
@import "./lib/style/mixins.less";
@import "./lib/style/features/button.less";
@import "./lib/style/features/clearfix.less";
@import "./lib/style/features/color.less";
@import "./lib/style/features/grid.less";
@import "./lib/style/features/indicator.less";
@import "./lib/style/features/line.less";
@import "./lib/style/features/list.less";
@import "./lib/style/features/popup.less";
@import "./lib/style/features/reset.less";
@import "./lib/style/features/scroll-nav.less";
@import "./lib/style/features/single-line.less";
@import "./lib/style/features/text.less";
@import "./lib/style/features/uploader.less";

@font-face {
    font-family: 'iconfont';  /* Project id 1578881 */
    src: url('//at.alicdn.com/t/font_1578881_hr4zmy75kqa.woff2?t=1623144915189') format('woff2'),
        url('//at.alicdn.com/t/font_1578881_hr4zmy75kqa.woff?t=1623144915189') format('woff'),
        url('//at.alicdn.com/t/font_1578881_hr4zmy75kqa.ttf?t=1623144915189') format('truetype');
}

page,
html,
body,
// 目前来看#app没有生效，虽然在代码中真的看到了，修改成.app后成功
.app {
    padding: 0;
    margin: 0;
    height: 100%;
    background-color: @color-white;

    &__indicator-wrap {
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
    }
}

.icon {
    font-family: 'iconfont';
    i& {
        font-style: normal;
    }
}
.fl {
    float: left;
}
.fr {
    float: right;
}
.line {
    position: relative;
    text-align: center;
    .line-content {
        position: relative;
        display: inline-block;
        padding: 20rpx 30rpx;
        .text-normal();
        color: #9b9b9b;
        background: @default-bg-color;
        z-index: 1;
    }
    &:after {
        content: '';
        position: absolute;
        left: 30rpx;
        right: 30rpx;
        top: 50%;
        height: 1px;
        background-color: #ebebeb;
    }
}
.default-box-shadow {
    box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.4);
}
.bottom-fixed {
    position: fixed;
    left: 0;
    bottom: 0;
}
.position-relative {
    position: relative;
}
.border-round {
    border-radius: 50%;
}
.section-gap {
    height: 10px;
    background-color: @default-bg-color;
}

// bind
.bind-popup {
    padding: 30px 20px;
    border-radius: 2px;
    &__content {
        position: relative;
    }
    &__hint {
        .text-large();
        .font-bold();
        text-align: center;
    }
    &__btn-wrap {
        padding-top: 20px;
    }
    &__btn {
        min-width: 208px;
        text-align: center;
        box-sizing: border-box;
    }
}

.hidden-object {
    position: absolute;
    left: 0;
    top: 0;
    width: 0;
    height: 0;
    opacity: 0;
}
</style>
